<%
var UploadClass=Class.create();
	UploadClass.prototype=
	{		
		initialize:function($options)
		{
			$options=($options||{});
			
			this.charSet=($options.charset||'UTF-8');
			this.type=($options.type||'jpg|jpeg|gif|png|bmp');
			this.autoSave=($options.autoSave==true ? true:false);
			this.autoSaveType=($options.autoSaveType||'All');		//All Or Any
			this.path=($options.path||'/UpFiles/');
			this.totalSize=($options.totalSize||(4*(1024<<10)));	//4M						
			this.maxSize=($options.maxSize||(200*1024));			//200K
						
			this.stream=Server.CreateObject('ADODB.Stream');
			this.stream.type=1;
			this.stream.Open();				
			this.tempStream=Server.CreateObject('ADODB.Stream');	
								
			this.formData={},this.fileCdatalog={};
			this.error=0,this.description=null;
			this.uploadLog={},this.uploadCount=0;
		},																				
		open:function()
		{
			try
			{
				if(Request.ServerVariables('REQUEST_METHOD').Item!='POST') throw 'Form method error 1';
				if(Request.ServerVariables('CONTENT_TYPE').Item.indexOf('multipart/form-data')==-1) throw 'Form method error 2';
				if(Request.TotalBytes>=this.totalSize) throw 'Form data size error';

				var dataSize=Request.TotalBytes,chunkSize=1000*200;
				if(dataSize<=chunkSize)
				{
					this.stream.write(Request.BinaryRead(dataSize));
				}
				else
				{
					while(dataSize>chunkSize)
					{
						this.stream.write(Request.BinaryRead(chunkSize));
						dataSize-=chunkSize;
					}
					if(dataSize>0) this.stream.write(Request.BinaryRead(dataSize));
				}				
				
				this.stream.position=0;
				this.stream.type=adTypeText;
				this.stream.charset='ascii';
				if(!this.stream.EOS) this.spider(this.stream.readText(adReadAll));
				this.stream.position=0;
				this.stream.type=adTypeBinary;
			}
			catch(e)
			{
				if(e=='Form method error 1')
					throw new Error(cusErrors_0001_Extend$UploadClass);
				else if(e=='Form method error 2')
					throw new Error(cusErrors_0002_Extend$UploadClass);	
				else if(e=='Form data size error')
					throw new Error(cusErrors_0003_Extend$UploadClass);
				else
				{
					if(e!=cusFrameworkDo$Break&&Object.varType(e)!='string')							
						throw e;
					else
						throw new Error(e);							
				}					
			}
		},			
		spider:function($data)
		{
			var limit=$data.substring($data.indexOf("--")+2,$data.indexOf("\r\n",$data.indexOf("--")+2));			
							
			var start,finish,position3;
				start=$data.indexOf(limit);	
				
			var formElementName,fileName;
										
			while(start!=-1)						
			{
				//查找位置
				start+=(limit.length+2);
				finish=$data.indexOf(limit,start);				
				if(finish==-1) break;
				
				position3=$data.indexOf("\r\n\r\n",start);								
				if(position3==-1||position3>finish) break;
				position3+=4;
				
				//获取表单元素相关信息
				var head=this.toText(start,position3-start);	
				formElementName=head.match(/\sname=\"(.+?)\"/);
				formElementName=formElementName[1];								
				if(formElementName==undefined) break;				
				
				fileName=head.match(/\sfilename=\"(.+?)\"/);
				fileName=String(fileName).split(',')[1];
				
				//建模
				if(fileName==undefined)
				{
					this.formData[formElementName]=this.toText(position3,finish-position3-4);	
				}
				else
				{					
					//记录文件域的表单信息
					this.formData[formElementName]=fileName;				
					//获取文件信息
					var fileSize=(finish-position3-4);
					var fileInfo=this.getFileInfo(position3,fileSize);
					var fileExt=fileName.match(/\.(\w+)$/);
					
					if(fileExt!=undefined) fileExt=fileExt[1].toLowerCase();
												
					if(this.isImage(fileExt)==true)
					{
						if(fileInfo.isImage==true){	
							fileExt=fileInfo.ext;
						}
						else{
							return false;
						}
					}					
										
					//记录文件日志与表单日志
					this.fileCdatalog[formElementName]=
					{
						formElementName:formElementName,
						fileName:fileName,
						fileExt:fileExt,
						fileSize:fileSize,
						fileBinaryStartPosition:position3,
						height:fileInfo.height,
						width:fileInfo.width
					};
					//存储文件信息
					if(this.autoSave==true) 
					{
						this.uploadLog[formElementName]=this.saveToFile(formElementName,position3,finish-position3-4,fileExt,fileSize);												
					}
				}
				start=finish;															
			}
		},
		/*存取表单信息*/
		form:function($name)
		{
			return this.formData[$name];
		},
		/* 存取文件域中的文件 手动的方法 */			
		save:function($elementName,$options)
		{
			if(this.autoSave==true) return {isUpload:false,error:{number:1,description:'设置为自动上传时禁止调用此方法'}};
			if(this.fileCdatalog[$elementName]==undefined) return {isUpload:false,error:{number:2,description:'表单无此文件域'}};			
			$options=($options||{});
			if($options.type!=undefined) this.type=$options.type;
			if($options.path!=undefined) this.path=$options.path;
			if($options.maxSize!=undefined) this.maxSize=$options.maxSize;						
				
			if(this.chkFileExt(this.fileCdatalog[$elementName].fileExt)==false){
				return {isUpload:false,error:{number:4,description:'文件类型错误'}};			
			}		
			if(this.fileCdatalog[$elementName].fileSize>this.maxSize){
				return {isUpload:false,error:{number:3,description:'文件大小超过限制'}};
			}

			var tempFile=Server.MapPath(this.path+this.makeFileName(this.fileCdatalog[$elementName].fileExt));
			//上传文件
			this.folderObserver();			
			this.tempStream.type=adTypeBinary;
			this.tempStream.open();									
			this.stream.position=this.fileCdatalog[$elementName].fileBinaryStartPosition;
			this.stream.copyTo(this.tempStream,this.fileCdatalog[$elementName].fileSize);
			this.tempStream.saveToFile(tempFile,adTypeBinary);
			this.tempStream.close();
			
			//写上传日志
			return {isUpload:true,error:{number:0,description:''}};
		},
		/* 当autoSave设置为true时自动存取表单中的文件 */	
		saveToFile:function($elementName,$position,$length,$ext,$size)
		{
			if(this.fileCdatalog[$elementName]==undefined) return {isUpload:false,error:{number:2,description:'表单无此文件域'}};			
			
			if(this.chkFileExt(this.fileCdatalog[$elementName].fileExt)==false){
				return {isUpload:false,error:{number:4,description:'文件类型错误'}};			
			}		
			if(this.fileCdatalog[$elementName].fileSize>this.maxSize){
				return {isUpload:false,error:{number:3,description:'文件大小超过限制'}};
			}
									
			var tempFile=Server.MapPath(this.path+this.makeFileName(this.fileCdatalog[$elementName].fileExt));
			
			this.folderObserver();	
			this.tempStream.type=1;
			this.tempStream.open();									
			this.stream.position=$position;
			this.stream.copyTo(this.tempStream,$length);
			this.tempStream.saveToFile(tempFile,2);
			this.tempStream.close();
			
			//写上传日志
			return {isUpload:true,error:{number:0,description:''}};			
		},
		showUploadLog:function()
		{
			for(var ii in this.uploadLog)
			{
				println(ii,' {');
					for(var iii in this.uploadLog[ii])
					{
						if(iii=='error')
						{
							println(' ','error{');
							for(var iiii in this.uploadLog[ii][iii])
								println(' '+iiii+'='+this.uploadLog[ii][iii][iiii]);
							println(' }');								
							continue;
						}
						println(' '+iii+'  ='+this.uploadLog[ii][iii]);
					}
				println(' }');
			}			
		},
		makeFileName:function($ext)
		{
			var myDateObj=new Date();
			var myYear,myMonth,myDate,myDay,myHours,myMinutes,mySeconds;
				myYear=(myDateObj.getYear()).toString();
				myMonth=(myDateObj.getMonth()+1).toString();
				myDate=(myDateObj.getDate()).toString();
				myHours=(myDateObj.getHours()).toString();
				myMinutes=(myDateObj.getMinutes()).toString();
				mySeconds=(myDateObj.getSeconds()).toString();
				this.uploadCount+=1;
				return myYear+myMonth+myDate+myHours+myMinutes+mySeconds+this.uploadCount.toString()+'.'+$ext;						
		},
		toText:function($position,$length)
		{
			var tempText='';
			this.tempStream.type=adTypeBinary;
			this.tempStream.open();			
			this.stream.position=$position;
			this.stream.copyTo(this.tempStream,$length);				
			this.tempStream.position=0;
			this.tempStream.type=adTypeText;
			this.tempStream.charset=this.charSet;
			tempText=this.tempStream.readText(-1);
			tempText=tempText.replace(/\u0000/g,'');
			this.tempStream.close();
			return tempText;
		},			
		folderObserver:function()
		{
			var folder=String(Server.MapPath(this.path)).split("\\");
			var fso_temp=Server.CreateObject('Scripting.FileSystemObject')
				var temp='';
				for(var ifolder=0;ifolder<=folder.length-1;ifolder++)
				{
					temp+=folder[ifolder]+'\\';
					if(ifolder>0)
					{			
						var tempFolder=temp.substr(0,temp.length-1);
						if(!fso_temp.FolderExists(temp.substr(0,temp.length-1))) fso_temp.CreateFolder(tempFolder);
						//echo(temp.substr(0,temp.length-1))
					}
				}
				fso_temp=null;
		},
		chkFileExt:function($ext)
		{				
			var isTotal=(this.type.indexOf('|')!=-1);
			if(isTotal==true)
			{
				var extEnum=this.type.split('|');
				for(var iExt=0;iExt<extEnum.length;iExt++)
				{	
					if(extEnum[iExt]==$ext){
						return true;
					}
				}
				return false;
			}	
			else
			{
				return (this.type==$ext) ? true:false;	
			}	
		},
		isImage:function($ext)
		{				
			var imageExt=['jpg','jpeg','gif','png','bmp'];
			for(var iExt=0;iExt<imageExt.length;iExt++){	
				if(imageExt[iExt]==$ext) return true;						
			}
			return false;
		},		
		getFileInfo:function($position,$length)
		{
			var ret = [null, 0, 0], tmp, arr,isImage=false;
			this.tempStream.type=1;
			this.tempStream.open();			
			this.stream.position=$position;
			this.stream.copyTo(this.tempStream,$length);				
			this.tempStream.position=0,this.tempStream.type=2;								
			this.tempStream.charset="UTF-16BE";
			var tmp=this.tempStream.readText(12);	
			var arr=tmp.toBytes();
			if (arr[0] == 0x47 && arr[1] == 0x49 && arr[2] == 0x46)
			{
				ret[0] = "gif",isImage=true;
				ret[1] = arr[7] << 8|arr[6];
				ret[2] = arr[9] << 8|arr[8];					
			}
			else if (arr[6] == 0x4A && arr[7] == 0x46 && arr[8] == 0x49 && arr[9] == 0x46)
			{
				ret[0] = "jpg",isImage=true;
				this.tempStream.position = 3;
				arr = this.tempStream.readText(-1).toBytes();
				var i = 0, k = 0, j = 0;
				while (true)
				{
					while ((i = arr[j++]) == 255);
					if (j > arr.length) break;
					if (i > 191 && i < 196) break;
					k = (arr[j++]) << 8|arr[j++];
					if ((j += k - 2) > arr.length) break;
					while ((i = arr[j++]) < 255);
					if (j > arr.length) break;
				}
				j += 3;
				if (j + 4 < arr.length)
				{
					ret[2] = (arr[j++] << 8)|arr[j++];
					ret[1] = (arr[j++] << 8)|arr[j++];
				}
			}				
			else if (arr[1] == 0x50 && arr[2] == 0x4E && arr[3] == 0x47)
			{
				ret[0] = "png",isImage=true;
				ret[1] = arr[18] << 8|arr[19];
				ret[2] = arr[22] << 8|arr[23];
			}
			else if(arr[0] == 0x42 && arr[1] == 0x4D)
			{
				ret[0] = "bmp",isImage=true;
				ret[1] = arr[19] << 8|arr[18];
				ret[2] = arr[23] << 8|arr[22];
			}	
			this.tempStream.close();			
			return {isImage:isImage,ext:ret[0],width:ret[1],height:ret[2]};
		},						
		close:function()
		{
			Object.clear(this);		
		}			
	};
%>